<template>
	<div class="about">
		<el-page-header @back="goBack"/>
		<el-form label-width="120px" @submit.native.prevent="save">
		<el-row style=" display: flex;justify-content:flex-start;align-items:center">
			<h1 class="h1">{{id ? '编辑':'新建'}}文章 </h1>
				
			<el-form-item>
				<el-button 
						size="small" :loading="uploading" type="primary"
						native-type="submit">保存</el-button>
				</el-form-item>
		</el-row>
			<el-row :gutter="10">
			<el-col :span="14" :gutter="5"><div class="grid-content bg-purple">
			<el-form-item label="所属赛事" style="font-weight: 700;">
				<el-select v-model="model.categories" style="width:32rem">
					<el-option
					v-for="item in categories"
					:key="item._id"
					:label="item.name"
					:value="item.name"
					multiple
					placeholder="请选择"/>
				</el-select>
			</el-form-item>
			<el-form-item label="标题" style="font-weight: 700;">
				<el-input v-model="model.title" style="width:32rem" placeholder="请输入"></el-input>
			</el-form-item>
				<el-form-item label="内容" style="font-weight: 700;">
					<editor v-model="model.body"></editor>

					<!--<el-upload
					style="display: none"
					:action=qiniuUrl	:http-requst = this.$qiniu
					:headers="getAuthHeaders()"
					:show-file-list="false"
					:on-success="afterUpload"
					:before-upload="beforePictureUpload">
					</el-upload>
					<el-upload
					style="display: none"
					:action=qiniuUrl	:http-requst = this.$qiniu
					:show-file-list="false"
					:on-success="afterUploadFile">
					</el-upload>-->
					
			</el-form-item>
			
			</div></el-col>
			<el-col :span="10"><div class="grid-content bg-purple-light">
			<el-row type="flex" justify="start">
			<el-form-item>
				<label style="font-weight: 700;">文章分类</label>
				<el-checkbox-group 
					v-model="model.tags">
					<el-checkbox v-for="option in options" :label="option" :key="option" :value="option">{{option}}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			</el-row>
			<el-row justify="start">
				<el-form-item >
					<label style="font-weight: 700;">文章封面图</label>
				<cover-uploader></cover-uploader>
				</el-form-item>
			</el-row>
			<br>
			<el-row>
				<el-form-item>
					<label style="font-weight: 700;">附件</label>
				<el-upload class="upload-demo"
					:http-request = this.$qiniu :action=qiniuUrl
					:on-remove="handleFilesRemove" :before-remove="beforeRemove" multiple
					:file-list="model.files">
					<el-button :loading="uploading"
					size="small" type="primary">点击上传</el-button>
				</el-upload>
			</el-form-item>
			</el-row>
			<el-row type="flex" justify="space-between">
				<el-form-item label="审核">
						<el-radio-group v-model="model.check">
							<el-radio-button label="通过"></el-radio-button>
							<el-radio-button label="不通过"></el-radio-button>
						</el-radio-group>
					</el-form-item>
			</el-row>
			</div></el-col>
			
			</el-row>
		</el-form>
	</div>
</template>

<script>
	import Editor from '../components/Editor'
	import coverUploader from '../components/CoverUploader'
	const articleOptions = ['竞赛通知', '竞赛介绍', '竞赛交流培训', '赛事动态', '赛事成果'];
	
	export default {
		components: {
			editor:Editor,
			coverUploader,
		},
		props: {
			id: {}
		},
		data() {
			return {
				model: {
					picture:'',
					cover:'',
					tags:[],
					categories:[],
					editTime:'',
					createTime:'',
					files:[],
				},
				options: articleOptions,
				categories: [],
				uploading: false,
				uploadingFile:'',
				percentage:0,
				//这是根据你七牛云创建空间时所选择的地区
				qiniuUrl : 'https://upload-z2.qiniup.com'
			}
		
		},
		methods: {
			goBack() {
				this.$router.go(-1)
			},
			async save() {
				let res
				const time = Date.now()
				const date = new Date(time)
				const year = date.getFullYear()
				const month = date.getMonth()+1
				const day = date.getDate()
				if (this.model.title == null || this.model.title.length == 0) {
					this.$message({
						type: 'warning',
						message: '内容不能为空'
					})
				} else {
					if (this.id) {
						console.log(year+'-'+month+'-'+day)
						this.model.editTime = year+'-'+month+'-'+day
						// 编辑
						res = await this.$http.put(`rest/articles/${this.id}`, this.model)
						console.log(res.data.body)
						this.$message({
							type: 'success',
							message: '保存成功'

						})
						
					} else {
						console.log(year+'-'+month+'-'+day)
						this.model.createTime = year+'-'+month+'-'+day
						this.model.editTime = year+'-'+month+'-'+day
						this.model.editor_id = this.$store.state.user.id
						//新建
						res = await this.$http.post('rest/articles', this.model)
						console.log(res.data)
						this.$router.push('/articles/list')
						this.$message({
							type: 'success',
							message: '新建成功'
						})
					}
				}
			},
			async pass(){
				this.model.check = "通过审核"
				await this.$http.put(`rest/articles/${this.id}`, this.model)
				this.$router.push('/articles/list')
				this.$message({
					type: 'success',
					message: '审核通过！'
				})
			},
			async fail(){
				this.model.check = "审核未通过"
				await this.$http.put(`rest/articles/${this.id}`, this.model)
				this.$router.push('/articles/list')
				this.$message({
					type: 'warning',
					message: '审核不通过！'
				})
			},
			async fetch() {
				const res = await this.$http.get(`rest/articles/${this.id}`)
				this.model = res.data
				this.$store.commit('setArticleContent',res.data.body)
				this.$store.commit('setCover',this.model.cover)
			},
			async fetchContests() {
				const res = await this.$http.get(`rest/contests`)
				this.categories = res.data
				console.log(this.categories)
			},
			
			afterCoverUpload(res){
				this.$set(this.model,'cover',res.url)
			},
			
			// 验证文件合法性
			beforeUpload (file) {
			const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
			const isLt2M = file.size / 1024 / 1024 < 2
			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!')
			}
			return isJPG && isLt2M
			},

			afterUpload(res) {
				if (res) {
						console.log("!")
					} else {
						// 提示信息，需引入Message
						this.$message({
								message: '图片插入失败',
								type: 'warning'
								});
					}
			},
			
			afterUploadFile(res) {
				if (res) {
						console.log("!")
				} else {
						// 提示信息，需引入Message
						this.$message({
								message: '文件插入失败',
								type: 'warning'
							});
					}
			},
			
			beforePictureUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},

			beforeRemove(file) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			},

			handleFilesRemove(file, fileList) {
				for (var i = 0; i < fileList.length; i++) {
					if (fileList[i] == file){
						fileList.splice(i,1)
					}
				}
				this.model.files = fileList
			},
		},
		created() {
			this.id && this.fetch()
			this.fetchContests()
		},
		computed: {
			//这里需要把store动态的数据放到computed里面才会同步更新视图
			getFiles(){
				console.log(this.$store.state.files)
                return this.$store.state.files
            },
			getCompressedFile(){
				console.log(this.$store.state.compressed_files)
                return this.$store.state.compressed_files
            },
			getUploading(){
				console.log(this.$store.state.uploading)
                return this.$store.state.uploading
            },
			getArticleContent(){
                return this.$store.state.article_content
            }
		},
		watch:{
			getFiles(newFile){
				switch(newFile.file_type){
					case 'file':
						this.model.files.push({"name":newFile.name, "url":newFile.url,})
						break
					case 'video':
						this.model.videos.push({"name":newFile.name, "url":newFile.url,})
						break
					case 'compressed_file':
						this.model.compressed_files.push({"name":newFile.name, "url":newFile.url,})
						break
					case 'cover':
						this.model.cover = newFile.url
						break
				}
				this.uploading=this.$store.state.uploading
				console.log("!"+newFile)
			},
			getCompressedFile(newFile){
				this.model.files.push({"name":newFile.name, "url":newFile.url})
				this.uploading=this.$store.state.uploading
				console.log(newFile.url)
            },
			getUploading(newInfo){
				this.uploading = newInfo.status
				this.percentage = newInfo.percentage
				console.log(this.percentage)
			},
			getArticleContent(newInfo){
				this.model.body = newInfo
				console.log(newInfo)
			}
		},
	}
</script>

<style>
.h1{
	font-size: 20px;
}
</style>